package cur.nature.component.nacos.handler;

import cur.nature.component.nacos.util.NacosContextUtil;
import cur.nature.component.nacos.property.MicroPropertyBean;
import cur.nature.component.nacos.property.MicroPropertyConfig;
import cur.nature.framework.core.log.LOG;
import cur.nature.framework.core.thread.MyThreadLocal;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.client.support.HttpRequestWrapper;

import java.io.IOException;
import java.net.URI;

public class CustomClientHttpRequestInterceptor implements ClientHttpRequestInterceptor {

    @Override
    public ClientHttpResponse intercept(final HttpRequest request, byte[] body, final ClientHttpRequestExecution execution) throws IOException {
        LOG.info("ms intercept:" + request.getURI());
        // 找出 serverName, uri
        final String uri = request.getURI().getPath();
        final int index = uri.substring(1).indexOf("/");
        final String serviceName = uri.substring(1,index+1);
        final String path = uri.substring(index+1);
        // 根据 serviceName 找出配置信息
        final MicroPropertyConfig config = NacosContextUtil.getBean(MicroPropertyConfig.class);
        final MicroPropertyBean property = config.getProperty(serviceName);
        // 组装 url
        final String url = "http://" + serviceName + path;
        LOG.info("ms url: " + url);
        final HttpRequest newRequest = new HttpRequestWrapper(request) {
            @Override
            public URI getURI() { return URI.create(url); }
        };
        // 设置 secret
        newRequest.getHeaders().add(property.getAuthKey(),property.getAuthSecret());
        // 设置 traceid
        final Object traceId = MyThreadLocal.getCurrentThread().get(MyThreadLocal.TRACE_ID);
        final Object userId = MyThreadLocal.getCurrentThread().get(MyThreadLocal.USER_ID);
        newRequest.getHeaders().add(MyThreadLocal.TRACE_ID,String.valueOf(traceId));
        newRequest.getHeaders().add(MyThreadLocal.USER_ID,String.valueOf(userId));
        // 执行
        return execution.execute(newRequest, body);


//        final String url = "http://" + serviceName + "/" + uri;
//        return execution.execute(request, body);
    }
}
